package com.example.controller;

import com.example.pojo.entity.JobRecruiter;
import com.example.pojo.entity.JobSeeker;
import com.example.service.JobSeekerService;
import com.example.service.RecruiterService;
import com.example.util.JWTUtils;
import com.example.util.NotificationUtil;
import com.example.util.SmsUtil;
import com.example.vo.Result;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;
import jakarta.servlet.http.HttpServletRequest;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.Date;
import java.util.concurrent.TimeUnit;

/**
 * @author 小岁
 * @version 2023/10/9 19:29
 */
@RestController
@RequestMapping("JrLogin")
public class RecruiterLoginController {

    @Autowired
    private NotificationUtil notificationUtil;

    @Autowired
    private RecruiterService recruiterService;

    @Autowired
    private SmsUtil smsUtil;

    @Autowired
    private RedisTemplate redisTemplate;

    private static final String SECRET = "success";//盐值
    private static String SECRET_KEY;

    /**
     * @Description:发送手机验证码
     * @Param:手机号码
     * @return:1表示成功，0表示失败
     */
    @RequestMapping(value = "/SendSMS/{username}")
    public Result SMSTest(@PathVariable("username") String phoneNumber, HttpServletRequest request) {
        ValueOperations vop = redisTemplate.opsForValue();
        Date date = new Date();
        long dat = date.getTime();
        if (vop.get(phoneNumber+"Time")!=null && dat-Long.parseLong(String.valueOf(vop.get(phoneNumber+"Time")))<60000){
            return new Result(502,"发送频繁");
        }


        System.out.println(phoneNumber);
        // 生成验证码
        String code = smsUtil.sendCode();
        System.out.println("验证码："+code);

        // 发送短信
//        boolean result = smsUtil.sendSms(phoneNumber, code);
        boolean result = true;


        if (!result) {// 发送不成功
            System.out.println("=================================");
            return new Result(500,"验证码发送失败");

        } else {
//            vop.set(phoneNumber,code,5, TimeUnit.MINUTES);
            vop.set(phoneNumber,code,5, TimeUnit.MINUTES);

//            redisTemplate.expire(phoneNumber,5,TimeUnit.HOURS);

            vop.set(phoneNumber+"Time", String.valueOf(System.currentTimeMillis()),12,TimeUnit.HOURS);
            // 将数据存入SESSION
//            request.getSession().setAttribute("checkCode", code);
//            // 将验证码生成时间存入SESSION，若超过五分钟则不通过校验
//            request.getSession().setAttribute("createTime", System.currentTimeMillis());
            return new Result(200,"验证码发送成功");
        }
    }

    /**
     * @Description:校验验证码是否正确
     * @Param:验证码
     * @return:成功返回OK，验证码超时返回TimeOut，验证码错误返回CodeError
     */
    @RequestMapping(value = "/checkSMSCode/{username}/{password}")
    public Result checkSMSCode(@PathVariable("username") String phoneNumber, @PathVariable("password") String checkSMSCode, HttpServletRequest request) {
//        request.getSession().setAttribute("checkCode", 252427);
//        request.getSession().setAttribute("createTime", System.currentTimeMillis());
        JobRecruiter jobRecruiter = recruiterService.jrLogin(phoneNumber);
        ValueOperations vop = redisTemplate.opsForValue();

        String serverCheckCode = (String) vop.get(phoneNumber);
        System.out.println();

        String serverCreateTime = (String) vop.get(phoneNumber+"Time");

        // 服务器放入的验证码
//        String serverCheckCode = request.getSession().getAttribute("checkCode").toString();
//        System.out.println(serverCheckCode+"===================================");

//        // 验证码创建时间
//        String serverCreateTime = request.getSession().getAttribute("createTime").toString();

        // 当前时间
        long uCreateTime = Long.parseLong(String.valueOf(System.currentTimeMillis()));


        if ( serverCreateTime == null || "".equals(serverCheckCode) || "".equals(serverCreateTime)) {
            return new Result(500,"验证码发送失败",serverCheckCode);
        }

        if (!checkSMSCode.equals(serverCheckCode)) {// 验证码不匹配
            return new Result(500,"验证码不匹配",checkSMSCode);
        }

        long sCreateTime = Long.parseLong(serverCreateTime);// 验证码创建时间

        if (serverCheckCode == null ||uCreateTime - sCreateTime >= 300000) {// 如果时间大于五分钟
            return new Result(500,"验证码已过期");
        }

        //校验是登录还是注册
        if (jobRecruiter != null) {

            redisTemplate.delete(phoneNumber);
            String token = JWTUtils.geneJsonWebToken(jobRecruiter);
            Integer userId = jobRecruiter.getId();
            vop.set("jr_"+userId,token);
            redisTemplate.expire("jr_"+userId,1, TimeUnit.HOURS);
            return new Result(200, "号码已存在，可以登录",userId,token);


        } else {

            checkSMSCode = Jwts.builder().claim("password","X123456").signWith(SignatureAlgorithm.HS256,SECRET).compact();
            int count = recruiterService.jrRegister(phoneNumber, checkSMSCode, phoneNumber);

            if (count != 0) {
                jobRecruiter = recruiterService.login(phoneNumber);
                redisTemplate.delete(phoneNumber);
               String token = JWTUtils.geneJsonWebToken(jobRecruiter);
//                return new Result(200, "注册完成，可以登录",JRtoken);
                Integer userId= jobRecruiter.getId();
                vop.set("jr_"+userId,token);
                redisTemplate.expire("jr_"+userId,1, TimeUnit.HOURS);
//                注册成功发送消息
//                notificationUtil.sendSms(phoneNumber);

                return new Result(200, "登录成功", userId,token);

            }

        }
        return new Result(501,"错误");

    }
}